<?php
namespace App\Http\Controllers\Api;

use App\Models\BookShelf;
use Illuminate\Http\Request;
use App\Models\Books;
use Illuminate\Support\Facades\Input;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Redis;
use App\Jobs\ClickQueue;

class BooksController extends Controller{

    /**
     * 小说详情
     * @param int $bookId 小说ID
     * @return [json] data object
     */
    public function detail(){

        $bookId = Input::get('id');
        if ($bookId == 0){
            return jsonErrorData('INVALID_PARAM');
        }
        //获取小说详情
        $data = Books::getBookDetailById($bookId);

        $data['isBookShelf'] = 0;

        $user = auth('api')->user();
        if (!empty($user)){
            $data['isBookShelf'] = BookShelf::isBookShelf($user->id,$bookId);
        }

        //点击量redis队列异步处理
        ClickQueue::dispatch(['id' => $bookId])->onQueue(config('cacheKey.clickList'));

        return jsonSuccessData($data);
    }

    /**
     * 小说章节内容
     * @param int $bookId 小说ID
     * @param int $chapter_id 章节ID
     * @return [json] data object
     */
    public function readContent(){
        $bookId = Input::get('id');
        $chapter_id = Input::get('chapter_id');

        if ($bookId == 0 || $chapter_id == 0){
            return jsonErrorData('INVALID_PARAM');
        }

        $chapter_tableName = chapterTableNameByBookId($bookId);
        //获取章节信息
        $chapter_data = DB::table($chapter_tableName)->select(['title','oss_url','sort'])->whereId($chapter_id)->first();
        if(empty($chapter_data)){
            return jsonErrorData('INVALID_PARAM');
        }

        $key = config('cacheKey.bookContent').$bookId;
//        $data = unserialize(Redis::hget($key,$chapter_id));
        if (empty($data)){
            $data = Books::select(['id','name'])->find($bookId);

            $book_url = config('oss.OSSDomain').$chapter_data->oss_url;
            /*打开远程文件txt获取内容*/
            $file_headers = @get_headers($book_url);
            //判断远程文件是否存在
            if($file_headers[0] != 'HTTP/1.1 200 OK'){
                return jsonErrorData('INVALID_FILE');
            }
            $handle = fopen($book_url, 'r');
            $content = '';
            while(!feof($handle)){
                $content .= fgets($handle).'<br>';
            }
            fclose($handle);
            /*去除章节内容里标题*/
            $data['title'] = $chapter_data->title;
            $data['content'] = preg_replace('/###([^^]*?)+###/','',$content,1);
//            $data['content'] = implode('<br>',array_slice(explode('<br>',$data['content']),7));
            $data['index'] = $chapter_data->sort;
//            Redis::hset($key,$chapter_id,serialize($data));
        }
        /*获取上一页下一页的章节ID*/
        $lastObj = DB::table($chapter_tableName)->whereBook_id($bookId)->where('sort','<',$chapter_data->sort)->orderBy('sort','desc')->first(['id']);
        $data['last_chapterId'] = isset($lastObj->id)?$lastObj->id:'0';
        $nextObj = DB::table($chapter_tableName)->whereBook_id($bookId)->where('sort','>',$chapter_data->sort)->orderBy('sort','asc')->first(['id']);
        $data['next_chapterId'] = isset($nextObj->id)?$nextObj->id:'0';

        return jsonSuccessData($data);
    }
}